<template>
  <section :class="isAll ? 'content w64vw' : 'content'">
    <div class="header">
      <div class="head-tit">电子合同</div>
      <div class="mlr15">
        <template v-for="(item, index) in buttonList">
          <el-button :key="index"
                     type="primary"
                     :plain="[0].includes(item.type)"
                     @click="submit(item.type)">{{item.label}}</el-button>
        </template>
      </div>
      <div class="line"></div>
    </div>
    <div v-if="(isPreview && !pdfUrl) || info.signMode === 1"
         class="mt20">
      <div class="all_center">
        <h3>{{info.contractName}}</h3>
        <div>合同有效期<span> {{info.effectiveDate}}</span> 至 <span>{{info.expireDate}}</span></div>
      </div>
      <div class="body_sty">
        <p>甲方：{{info.tenantNameOne}}</p>
        <p>乙方：{{info.tenantNameTwo}}</p>
        <div class="mtb40">
          <p v-html="info.contentBody"></p>
        </div>
        <p>附件：</p>
        <div>
          <template v-for="(ele, i) in getFile()">
            <span :key="i"
                  class="file_sty pointer"
                  @click="downloadTemplate(ele.url)">
              <icon-svg :icon-name="ele.icon"
                        class="mr3" />{{ele.name}}
            </span>
          </template>
        </div>
        <div class="flex-between">
          <div>
            <p>甲方（盖章）：{{info.tenantNameOne}}</p>
            <p>甲方代表人：{{info.sealUserNameOne}}</p>
            <p v-if="partya">签订日期：{{info.signDateOne}}</p>
          </div>
          <div>
            <p>乙方（盖章）：{{info.tenantNameTwo}}</p>
            <p>乙方代表人：{{info.sealUserNameTwo}}</p>
            <p v-if="partyb">签订日期：{{info.signDateTwo}}</p>
          </div>
        </div>
      </div>
    </div>
    <iframe v-else
            id="iframeId"
            :src="pdfUrl"
            width="100%"
            height="900px" />
    <reject :id="contractId"
            :label="'refusalReason'"
            :api="api.refuse"
            :title="'拒绝原因'"
            id-name="contractId"
            :is-close="false"
            :visible.sync="visible"
            @back="back" />
  </section>
</template>
<script>
import Reject from "@/views/quote/transport/components/Reject.vue";
import { contract } from "@/api/index.js";
export default {
  name: "ContractPreview",
  components: {
    Reject
  },
  data () {
    return {
      api: contract,
      buttonList: [
        { label: "返回", type: 0 },
        { label: "保存", type: 1 },
        { label: "签署", type: 2 },
      ],
      info: {},
      pdfUrl: null,
      visible: false,
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    // ...mapState({
    //   login: (state) => state.login
    // }),
    login () {
      return JSON.parse(this.userInfo)
    },
    contractId () {
      return this.$route.query?.contractId || this.$route.params?.contractId
    },
    isPreview () {
      return this.$route.query?.isPreview
    },
    isSended () {
      return this.$route.query?.isSended
    },
    // 入口是否为承运方/发货方-电子合同
    isAll () {
      const { name } = this.$route
      return name === 'contractPreviewWindow'
    },
    partya () {
      const { contractStatus, contractType, signDateOne } = this.info;
      return (contractStatus !== 4 && contractType === 2 && signDateOne) || contractStatus === 4;
    },
    partyb () {
      const { contractStatus, contractType, signDateTwo } = this.info;
      return (contractStatus !== 4 && contractType === 1 && signDateTwo) || contractStatus === 4;
    }
  },
  created () {
    this.info = this.$route.params
    if (this.$route.query?.pdfUrl) {
      this.pdfUrl = this.$route.query?.pdfUrl
      this.buttonList = [{ label: "返回", type: 5 }]
    }
    if (this.contractId && !this.isPreview) {
      this.getDetails(this.isSended)
      this.buttonList = [{ label: "返回", type: 5 }]
    }
  },
  methods: {
    // 获取详情
    async getDetails (isSended, contractId) {
      let { data } = await contract.getDetail(contractId || this.contractId);
      this.info = { ...this.info, ...data };
      if (data.signMode === 2 && !data.fileStats) {
        this.$message({ type: "warning", message: "文件不存在" });
      }
      if (data.signMode === 2) {
        this.getPdfUrl()
      }
      if (!isSended) {
        switch (data.contractStatus) {
          case 1:
            this.buttonList = [
              { label: "返回", type: 0 },
              { label: "保存", type: 1 },
              { label: "签署", type: 2 },
            ]
            break;
          case 2:
            if ((data.contractType === 2 && this.login.tenantId === data.tenantIdOne) || data.contractType === 1 && this.login.tenantId === data.tenantIdTwo) {
              this.buttonList = [
                { label: "返回", type: 0 },
                { label: "撤回", type: 6 },
              ]
            } else {
              this.buttonList = [
                { label: "返回", type: 0 },
                { label: "拒绝", type: 3 },
                { label: "签署", type: 4 },
              ]
            }
            break;
          case 3:
            this.buttonList = [
              { label: "返回", type: 0 },
            ]
            break;
          case 4:
            this.buttonList = [
              { label: "关闭", type: 0 },
            ]
            break;
          case 5:
            this.buttonList = [
              { label: "关闭", type: 0 },
            ]
            break;
        }
      }
    },
    // 获取pdf
    async getPdfUrl () {
      let { data } = await contract.getPdfUrl(this.contractId);
      this.pdfUrl = data.includes('https') ? data : data.replace('http', 'https')
    },
    // 触发事件
    submit (val) {
      if ([0].includes(val)) {
        this.back()
      } else {
        switch (val) {
          case 1:
            if (this.contractId) {
              this.update()
            } else {
              this.create(1)
            }
            break;
          case 2:
            this.handleSign('sendout');
            break;
          case 3:
            this.refuse();
            break;
          case 4:
            this.handleSign('sign');
            break;
          case 5:
            this.go();
            break;
          case 6:
            this.recall();
            break;
        }
      }
    },
    getFile () {
      let attachments = []
      if (this.info.contractAttachments.length) {
        attachments = this.info.contractAttachments.map((x) => {
          let suffix = x.name.slice(x.name.indexOf(".") + 1, x.name.length);
          let icon = null
          if (["doc", "docx", "xls", "xlsx", "txt"].includes(suffix)) icon = "word"
          else if (["zip", "rar"].includes(suffix)) icon = "yasuo"
          else if (["pdf"].includes(suffix)) icon = "PDF"
          else if (["jpg", "png"].includes(suffix)) icon = "JPG"
          return {
            ...x,
            icon
          };
        });
      }
      return attachments
    },
    // 创建合同
    async create (contractStatus) {
      let { data } = await contract.createContract({ ...this.info, contractStatus });
      if (contractStatus === 1) {
        this.$message.success("已保存到草稿")
        this.go()
      } else {
        this.goContractDetail(data)
      }
    },
    // 修改合同
    async update (type) {
      await contract.updateContract({ ...this.info, contractId: this.contractId, contractStatus: 1 });
      if (type) {
        this.sendContract()
      } else {
        this.go()
      }
    },
    // 签署
    handleSign (type) {
      this.$confirm("确认是否签署合同", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (type === 'sign') {
          this.sign()
        } else {
          if (this.contractId) {
            this.update('sign')
          } else {
            this.create(2)
          }
        }
      });
    },
    // 发送合同
    async sendContract () {
      let { data } = await contract.sendContract({ contractId: this.contractId })
      this.goContractDetail(data)
    },
    // 发送后跳转
    goContractDetail (data) {
      if (data.includes('//')) {
        this.pdfUrl = data
      } else {
        this.getDetails(1, data)
      }
      this.buttonList = [{ label: "返回", type: 5 }]
    },
    // 签署合同
    async sign () {
      let { data } = await contract.sign({ contractId: this.contractId })
      this.goContractDetail(data)
    },
    // 拒绝
    refuse () {
      this.visible = true;
    },
    // 撤回
    recall () {
      this.$confirm("确认撤回合同吗?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.recallRes()
      });
    },
    async recallRes () {
      await contract.recall({ contractId: this.contractId })
      this.$router.back();
    },
    // 下载模板
    downloadTemplate (url) {
      let newUrl = url.includes('https') ? url : url.replace('http', 'https')
      window.location.href = newUrl
    },
    // 返回
    back () {
      for (let key in this.info) {
        this.$route.params[key] = this.info[key];
      }
      this.$router.back();
      window.close();
    },
    // 返回两级
    go () {
      this.$router.go(-2);
    },
  }
};
</script>
<style lang="scss" scoped>
.content {
  background: var(--prev-bg-white);
  position: relative;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
}
.w64vw {
  width: 64vw;
  margin-left: 18vw;
}
.header {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.head-tit {
  font-size: 20px;
  color: var(--prev-color-text-black);
  font-weight: 500;
  line-height: 60px;
  margin-left: 15px;
}
.line {
  width: 100%;
  border-bottom: 4px solid var(--prev-icon-color-orange);
  position: absolute;
  top: 56px;
}
.mlr15 {
  margin-left: 15px;
  margin-right: 15px;
}
.all_center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  h3 {
    font-size: 20px;
  }
  span {
    color: var(--prev-color-primary);
  }
}
.body_sty {
  padding: 20px 60px;
}
.mtb40 {
  margin-top: 40px;
  margin-bottom: 40px;
}
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
}
.file_sty {
  color: var(--prev-color-primary);
  margin-right: 15px;
}
.mr3 {
  margin-right: 3px;
}
.mt20 {
  margin-top: 20px;
}
</style>
